package vip.liux.front.application.service.product;

import org.springframework.stereotype.Service;
import vip.liux.application.dots.ListResultDto;
import vip.liux.contracts.models.product.Category;
import vip.liux.contracts.repositories.product.CategoryRepository;
import vip.liux.contracts.shared.enums.product.CategoryType;
import vip.liux.contracts.shared.value.LevelModel;

import java.util.stream.Collectors;

@Service
public class CategoryService {
    private final CategoryRepository categoryRepository;

    public CategoryService(CategoryRepository categoryRepository) {
        this.categoryRepository = categoryRepository;
    }

    public ListResultDto<CategoryDto> list(CategoryType type) {
        return new ListResultDto<>(
                LevelModel.buildTree(
                        categoryRepository.findByType(type).stream().map(this::toDto).collect(Collectors.toList()),
                        CategoryDto::getCatNo,
                        CategoryDto::getParentNo
                )
        );
    }

    private CategoryDto toDto(Category category) {
        return AutoMapperProfile.INSTANCE.toDto(category);
    }
}
